package sanbing.jcpplearning;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;

public class NettyServer {
    public static void main(String[] args) throws Exception {
        // 主线程组，用于接收客户端连接
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 工作线程组，用于处理已接收的连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 服务端启动器
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup) // 绑定线程组
                    .channel(NioServerSocketChannel.class) // 指定服务端通道类型
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加 HTTP 编解码器
                            pipeline.addLast(new HttpServerCodec());
                            // 添加 HTTP 报文聚合器，方便处理完整的 HTTP 请求
                            pipeline.addLast(new HttpObjectAggregator(65536));
                            // 添加自定义处理器
                            pipeline.addLast(new CustomHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128) // 服务端接受连接的队列大小
                    .childOption(ChannelOption.TCP_NODELAY, true) // 禁用 Nagle 算法，降低延迟
                    .childOption(ChannelOption.SO_KEEPALIVE, true); // 开启 TCP 长连接

            // 绑定端口并启动
            ChannelFuture future = bootstrap.bind(8080).sync();
            System.out.println("HTTP 服务端启动成功，端口 8080");
            // 阻塞当前线程，直到服务器通道关闭
            future.channel().closeFuture().sync();
        } finally {
            // 优雅关闭线程组
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    // 自定义处理器，用于处理 HTTP 请求
    static class CustomHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
            // 打印收到的 HTTP 请求信息
            System.out.println("收到 HTTP 请求：");
            System.out.println("方法: " + request.method());
            System.out.println("URI: " + request.uri());
            System.out.println("内容: " + request.content().toString(io.netty.util.CharsetUtil.UTF_8));

            // 构建 HTTP 响应
            FullHttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, 
                    HttpResponseStatus.OK, 
                    io.netty.buffer.Unpooled.copiedBuffer("OK", io.netty.util.CharsetUtil.UTF_8)
            );
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

            // 将响应写入通道并刷新
            ctx.writeAndFlush(response);
        }
    }
}